//
//  FZComposeViewController.swift
//  FZSina_Swift
//
//  Created by 李忠 on 7/26/16.
//  Copyright © 2016 FZLZ. All rights reserved.
//

import UIKit

class FZComposeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = RANDRGB()
        setupNav()
        setupUI()
        setupLayout()
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func setupNav() {
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", imgName: nil, target: self, action: #selector(cancelButton))
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", imgName: nil, target: self, action: #selector(publishButton))
        self.navigationItem.rightBarButtonItem?.enabled = false
    }
    func setupUI() {
        view.addSubview(componseTextView)
        componseTextView.addSubview(componsePicture)
        view.addSubview(toolBar)
        
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(keyboardWillChange(_:)), name: UIKeyboardWillChangeFrameNotification, object: nil)
        //删除文本内容
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(deleteEmoticonButton), name: FZDELETEEMOTICONBUTTONNOTI, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(inputEmoticon(_:)), name: FZINPUTEMOTICONNOTI, object: nil)
        
    }
    func setupLayout(){
    
        componseTextView.snp_makeConstraints { (make) in
            make.edges.equalTo(UIEdgeInsetsZero)
        }
        
        componsePicture.snp_makeConstraints { (make) in
            make.size.equalTo(CGSizeMake(SCREENW - 20, SCREENW - 20))
            make.centerX.equalTo(componseTextView.snp_centerX)
            make.top.equalTo(100)
        }
        toolBar.snp_makeConstraints { (make) in
            make.leading.trailing.bottom.equalTo(0)
            make.height.equalTo(35)
        }
//        toolBar.snp_make
    }
//MARK:==========================添加事件==========================
    func cancelButton() {
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    func publishButton() {
        print("你好，再见！")
    }
    
    //MARK: 按钮发生改变执行的方法
    func keyboardWillChange(notic: NSNotification) {
        //UIKeyboardAnimationDurationUserInfoKey
        
        let duration = notic.userInfo!["UIKeyboardAnimationDurationUserInfoKey"] as! Double
        let move = notic.userInfo!["UIKeyboardFrameEndUserInfoKey"] as! NSValue
        let moveY = move.CGRectValue().origin.y
        
        toolBar.snp_updateConstraints { (make) in
            
            make.bottom.equalTo(self.view.snp_bottom).offset(moveY - SCREENH)
        }
        UIView.animateWithDuration(duration) { 
            self.toolBar.layoutIfNeeded()
        }
    }
    //MARK: 点击删除按钮执行的方法
    func deleteEmoticonButton() {
       componseTextView.deleteBackward()
    }
    
    //MARK: 
    func inputEmoticon(noti: NSNotification)  {
        let emoticon = noti.object as! FZEmoticonModel
        if emoticon.isEmoji {
            guard let icon = emoticon.code else{
                return
            }
            
            componseTextView.insertText((icon as NSString).emoji())
        }
    }
//MARK:==========================懒加载==========================
    lazy var componseTextView: FZComposeTextView = {
        let text: FZComposeTextView = FZComposeTextView()
        text.font = UIFont.systemFontOfSize(15)
        text.delegate = self
        text.placeholdText = "你是猪吗?你是猪吗?你是猪吗?你是猪吗?你是猪吗?你是猪吗?你是猪吗?你是猪吗?你是猪吗?你是猪吗?你是猪吗?你是猪吗?你是猪吗?你是猪吗?你是猪吗?"
        text.alwaysBounceVertical = true
        return text
    }()
    
    lazy var componsePicture: FZComponsePictureView = {
        
        let flowLayout = UICollectionViewFlowLayout()
        let picture: FZComponsePictureView = FZComponsePictureView(frame: CGRectZero, collectionViewLayout: flowLayout)
        picture.addImageCloure = {[weak self] in
            self?.presentViewController((self?.pickImage)!, animated: true, completion: nil)
        }
        return picture
    }()
    
    lazy var pickImage:UIImagePickerController  = {
        let pick = UIImagePickerController()
        pick.delegate = self
        return pick
    }()
    
    //MARK: 懒加载表情键盘
    lazy var emoticonView: FZEmoticonKeyboardView = {
        
        let emotic = FZEmoticonKeyboardView()
        return emotic
    }()
    
    lazy var toolBar:FZComposeToolBarView = {
        let tool = FZComposeToolBarView()
        tool.callBack = {[weak self](type) in
            switch type{
            case .Picture:
                
                self?.selectImage()
                break
            case .Mention:
                
                break
            case .Trend:
                
                break
            case .Emoticon:
                self?.emotionClik()
                break
            case .Add:
                
                break
            }
        }
        return tool
    }()
    
    
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
}

extension FZComposeViewController: UITextViewDelegate{
    func textViewDidChange(textView: UITextView) {
        
        self.navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    func scrollViewDidScroll(scrollView: UIScrollView) {
        
        componseTextView.resignFirstResponder()
    }
}


//MARK: 底部按钮调用方法
extension FZComposeViewController{
   private func selectImage(){

        self.presentViewController(pickImage, animated: true, completion: nil)
    }
    
    private func emotionClik(){
        
        componseTextView.becomeFirstResponder()
        if componseTextView.inputView == nil {
             componseTextView.inputView = emoticonView
        }else{
             componseTextView.inputView = nil
        }
        componseTextView.reloadInputViews()

    }
    
}

extension FZComposeViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate{
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        

        UIImage.cutIMG(image, scale: 600.0) { (img) in
        
            self.componsePicture.addImageForList(img)            
        }
        
        self.dismissViewControllerAnimated(true) { 
            
        }
        
        
    }
}